<template>
    <div :class='$style.addForm'>
        <el-tabs v-model='currentTab'>
            <el-tab-pane name='main' label='主要信息'>
                <XFormBox>
                    <el-form ref='formRef' :rules='rules' :model='formData' size='small' label-position='top'>
                        <el-form-item label='策略类型' prop='strategyType'>
                            <el-select class='w-100' clearable  v-model='formData.strategyType'>
                                <template v-for='item in chargeStrategryList' :key='item.code'>
                                    <el-option :value='item.code' :label='item.name'></el-option>
                                </template>
                            </el-select>
                        </el-form-item>
                        <el-form-item label='策略名' prop='strategyName'>
                            <el-input type='text' :maxlength='rules.strategyName[1].max' show-word-limit clearable v-model='formData.strategyName' />
                        </el-form-item>
                        <el-form-item label='单价' prop='unitPrice'>
                            <el-input type='text' clearable v-model='formData.unitPrice'>
                                <template #append>元 / {{strategyTypeName}}</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label='结算单位' prop='settleUnit'>
                            <el-input type='text' clearable v-model='formData.settleUnit'>
                                <template #append>{{formData.strategyType == 2 ? '度' : '分钟'}}</template>
                            </el-input>
                        </el-form-item>
                        <!-- <el-form-item label='最小功率' prop='minPower'>
                            <el-input type='text' clearable v-model.number='formData.minPower'>
                                <template #append>W</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label='最大功率' prop='maxPower'>
                            <el-input type='text' clearable v-model.number='formData.maxPower'>
                                <template #append>W</template>
                            </el-input>
                        </el-form-item> -->
                        <el-form-item label='刷卡预付费' prop='cardChargeAmount'>
                            <el-input type='text' clearable v-model='formData.cardChargeAmount'>
                                <template #append>元</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label='免费占位时长' prop='freeOccupyTime'>
                            <el-input type='text' clearable v-model.number='formData.freeOccupyTime'>
                                <template #append>分钟</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label='占位收费'>
                            <el-input type='text' clearable v-model='formData.occupyPrice'>
                                <template #append>元/小时</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item v-if='formData.strategyType == 1 || formData.strategyType == 3'>
                            <template #label>
                                <div>充电策略<span class='color-forbidden f-12'>（最少一项，最多四项）</span></div>
                            </template>
                            <div :class='$style.rules'>
                                <template v-for='(item, index) in formData.rules' :key='index'>
                                    <div :class='$style.rule'>
                                        <el-form-item :class='$style.ruleFormItem' :rules='stategyRulesPowerRule' :prop='"rules." + index + ".w"'>
                                            <el-input type='text' class='text-center' clearable v-model.number='item.w'></el-input>
                                        </el-form-item>
                                        <span :class='$style.text'>W</span>
                                        <el-form-item :class='[$style.ruleFormItem, "m-l-5"]' :rules='stategyRulesAmountRule' :prop='"rules." + index + ".a"'>
                                            <el-input type='text' class='text-center' clearable v-model='item.a'></el-input>
                                        </el-form-item>
                                        <span :class='$style.text'>元/小时</span>
                                        <template v-if='formData.rules.length > 1'>
                                            <el-icon :class='$style.delete' @click='deleteRule(index)'>
                                                <CloseBold />
                                            </el-icon>
                                        </template>
                                    </div>
                                </template>
                                <template v-if='formData.rules.length < 4'>
                                    <div class='text-center'>
                                        <el-icon class='pointer' @click='addRule'><plus /></el-icon>
                                    </div>
                                </template>
                            </div>
                        </el-form-item>
                        <el-form-item label='充电预设选项'>
                            <div :class='$style.options'>
                                <template v-for='(item, index) in formData.options' :key='index'>
                                    <el-form-item :class='$style.option' :rules='stategyRulesAmountRule' :prop='"options." + index'>
                                        <el-input type='text' class='text-center' align='center' v-model='formData.options[index]'></el-input>
                                        <el-icon :class='$style.delete' @click.stop='deleteOption(index)'>
                                            <CloseBold />
                                        </el-icon>
                                    </el-form-item>
                                </template>
                                <div class='text-center'>
                                    <el-icon class='pointer' @click='addOption'><plus /></el-icon>
                                </div>
                            </div>
                        </el-form-item>
                    </el-form>
                </XFormBox>
            </el-tab-pane>
            <el-tab-pane name='other' label='其它信息'>
                <XFormBox>
                    <el-form ref='otherFormRef' :rules='rules' :model='formData' size='small' label-position='top'>
                        <el-form-item label='是否充满自停'>
                            <el-switch v-model='formData.fullStop' />
                            <!-- <el-radio v-model='formData.fullStop' :label='1'>充满自停</el-radio>
                            <el-radio v-model='formData.fullStop' :label='0'>充满不自停</el-radio> -->
                        </el-form-item>
                        <el-form-item label='应急充电使能'>
                            <el-switch v-model='formData.emergCharge' />
                            <!-- <el-radio v-model='formData.emergCharge' :label='1'>使能</el-radio>
                            <el-radio v-model='formData.emergCharge' :label='0'>失能</el-radio> -->
                        </el-form-item>
                        <el-form-item label='应急充电次数' prop='emergCount'>
                            <el-input type='text' clearable v-model.number='formData.emergCount'></el-input>
                        </el-form-item>
                        <el-form-item label='应急充电电能' prop='emergEnergy'>
                            <el-input type='text' clearable v-model.number='formData.emergEnergy'>
                                <template #append>KWH</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label='充满临界功率' prop='fullPower'>
                            <el-input type='text' clearable v-model.number='formData.fullPower'>
                                <template #append>W</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label='判满延时' prop='fullDelay'>
                            <el-input type='text' clearable v-model.number='formData.fullDelay'>
                                <template #append>分钟</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label='拔掉停止延时' prop='plugOffDly'>
                            <el-input type='text' clearable v-model.number='formData.plugOffDly'>
                                <template #append>秒</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label='说明'>
                            <el-input type='textarea' :rows='3' maxlength='200' show-word-limit clearable v-model='formData.remark' />
                        </el-form-item>
                    </el-form>
                </XFormBox>
            </el-tab-pane>
        </el-tabs>
        <div class='text-center m-t-20'>
            <XRequestButton :click='submit'>
                <el-button size='mini' type='primary'>确 定</el-button>
            </XRequestButton>
        </div>
    </div>
</template>

<script lang='ts' setup>
    import { ElMessage } from 'element-plus'
    import { CloseBold, Plus } from '@element-plus/icons'
    import { addChargeStrategyApi, editChargeStrategyApi, getChargeStrategyEditDataApi } from '../../../api/chargeStrategy'
    import { filterEmpty, transformNumberString } from '../../../utils'
    import { computed, reactive, ref } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    import { queryDictionaryOfChargeStrategyTypeApi } from '../../../api/dictionary'

    const currentTab = ref('main')

    let strategyId = ref(0)
    const formData = reactive({
        strategyType : null,
        strategyName : null,
        unitPrice : null,
        settleUnit : 1,
        cardChargeAmount : null,
        rules : [{w : '', a : ''}],
        options : [],
        remark : null,


        freeOccupyTime:null,
        occupyPrice:null,

        fullStop : true,
        emergCharge : false,
        emergCount : null,
        emergEnergy : null,
        fullPower : 25,
        fullDelay : 10,
        plugOffDly : 60,
    })

    const chargeStrategryList = reactive([])

    const strategyTypeName = computed(() => {
        return formData.strategyType == 2 ? '度' : '小时'
    })

    let districts = reactive<string[]>([])
    let initSelectQuery = reactive({
        simCardNo : '',
        merchantName : ''
    })
    const rules = reactive<{[key in (keyof (typeof formData))]? : any}>({
        strategyType : [
            {
                required : true,
                message : '请选择策略类型'
            }
        ],

        strategyName : [
            {
                required : true,
                message : '请输入策略名'
            },
            {
                min : 1,
                max : 15,
                message: '策略名长度在1-15个字符之间',
            }
        ],

        unitPrice : [
            {
                required : true,
                type : 'number',
                min : 0,
                max : 100,
                validator(rule, value, callback) {
                    value = Number(value)
                    if(typeof value !== 'number' || isNaN(value) || value < rule.min || value > rule.max) {
                        callback(new Error(`单价必须在${rule.min}至${rule.max}之间`))
                    }else {
                        callback()
                    }
                }
            }
        ],

        settleUnit : [
            {
                required : true,
                type : 'number',
                min : 0,
                max : 100,
                validator(rule, value, callback) {
                    value = Number(value)
                    if(typeof value !== 'number' || isNaN(value) || value < rule.min || value > rule.max) {
                        callback(new Error(`结算单位必须在${rule.min}至${rule.max}之间`))
                    }else {
                        if(formData.strategyType != 2 && value != Math.floor(value)) {
                            callback(new Error(`计时模式结算单位必须是整数`))
                        }else {
                            callback()
                        }
                        
                    }
                }
            }
        ],

        cardChargeAmount : [
            {
                required : true,
                type : 'number',
                min : 0,
                max : 100,
                validator(rule, value, callback) {
                    value = Number(value)
                    if(typeof value !== 'number' || isNaN(value) || value < rule.min || value > rule.max) {
                        callback(new Error(`刷卡预付费必须在${rule.min}至${rule.max}之间`))
                    }else {
                        callback()
                    }
                }
            }
        ],

        freeOccupyTime : [
            {
                required : false,
                type : 'number',
                min : 0,
                max : 5000,
                message : '免费占位时长在0-5000分钟之间'
            }
        ],

        occupyPrice : [
            {
                required : true,
                type : 'number',
                min : 0,
                max : 100,
                validator(rule, value, callback) {
                    value = Number(value)
                    if(typeof value !== 'number' || isNaN(value) || value < rule.min || value > rule.max) {
                        callback(new Error(`占位收费必须在${rule.min}至${rule.max}之间`))
                    }else {
                        callback()
                    }
                }
            }
        ],

        emergCount : [
            {
                required : false,
                type : 'number',
                min : 0,
                max : 10,
                message : '应急充电次数在0-10次之间'
            }
        ],

        emergEnergy : [
            {
                required : false,
                type : 'number',
                min : 0,
                max : 200,
                message : '应急充电电能在0-200KWH之间'
            }
        ],

        fullPower : [
            {
                required : false,
                type : 'number',
                min : 0,
                max : 255,
                message : '充满临界功率在0-255W之间'
            }
        ],

        fullDelay : [
            {
                required : false,
                type : 'number',
                min : 0,
                max : 60,
                message : '判满延时在0-60分钟之间'
            }
        ],

        plugOffDly : [
            {
                required : false,
                type : 'number',
                min : 0,
                max : 200,
                message : '拔掉停止延时在0-200秒之间'
            }
        ]
    })

    const stategyRulesPowerRule = [
        {
            required : true,
            message : '请输入功率'
        },

        {
            type : 'number',
            min : 0,
            max : 10000,
            message : '功率在0-10000之间'
        }
    ]

    const stategyRulesAmountRule = [
        {
            required : true,
            type : 'number',
            min : 0,
            max : 1000,
            validator(rule, value, callback) {
                value = Number(value)
                if(typeof value !== 'number' || isNaN(value) || value < rule.min || value > rule.max) {
                    callback(new Error(`金额必须在${rule.min}至${rule.max}之间`))
                }else {
                    callback()
                }
            }
        }
    ]

    const formRef = ref()
    const otherFormRef = ref()
    const route = useRoute()
    const router = useRouter()


    function deleteRule(index:number) {
        formData.rules.splice(index, 1)
    }

    function addRule() {
        formData.rules.push({w : '', a : ''})
    }


    function addOption() {
        formData.options.push('')
    }

    function deleteOption(index:number) {
        formData.options.splice(index, 1)
    }

    async function submit() {
        try {
            await formRef.value.validate()
        } catch (error) {
            currentTab.value = 'main'
            return false
        }

        try {
            await otherFormRef.value.validate()
        } catch (error) {
            currentTab.value = 'other'
            return false
        }

        try {
            const data = {...formData}
            transformNumberString(data, ['strategyName', 'remark'])
            if(!strategyId.value) { //新增
                filterEmpty(data)
                const res = await addChargeStrategyApi(data)
                if(res.success) {
                    ElMessage.success!('增加成功')
                }else {
                    ElMessage.error!(res.msg)
                    return
                }
            }else {
                const res = await editChargeStrategyApi(strategyId.value, data)
                if(res.success) {
                    ElMessage.success!('编辑成功')
                }else {
                    ElMessage.error!(res.msg)
                    return
                }
            }

            router.go(-1)
        } catch (error) {
            
        }
        
    }

    async function init() {
        if(route.params.strategyId) {
            strategyId.value = Number(route.params.strategyId)
            const data:typeof formData = await getChargeStrategyEditDataApi(strategyId.value)
            
            if(!data) {
                ElMessage.error!('数据不存在')
                useRouter().go(-1)
            }else {
                for(let k in formData) {
                    transformNumberString(data, ['strategyName', 'remark'])
                    if(k in data) {
                        if(k == 'fullStop' || k == 'emergCharge') {
                            data[k] = Boolean(data[k])
                        }
                        formData[k] = data[k]
                    }
                }

                
            }
        }
    }

    queryDictionaryOfChargeStrategyTypeApi().then(rows => {
        formData.strategyType = rows[0].code
        chargeStrategryList.push(...rows)
    })

    init()

    

</script>

<style scoped lang='scss' module>
    .addForm{
        margin: auto;
        max-width: 800px;
    }

    .rules{
        display: grid;
        gap: 20px;
        grid-template-columns: repeat(2, 1fr);


        @media screen and (max-width:900px) {
            grid-template-columns: repeat(1, 1fr);
        }

        .rule{
            display: flex;
            align-items: center;
            position: relative;
            .text{
                white-space: nowrap;
                font-size: 12px;
                margin-left:5px;
            }

            &:hover{
                .delete{
                    display: block;
                }
            }
        }
        
        .ruleFormItem{
            flex: 1;
            text-align: center;
            margin-bottom: 0 !important;
        }
    }

    .options{
        display: grid;
        gap: 15px;
        grid-template-columns: repeat(6, 1fr);

        @media screen and (max-width:900px) {
            grid-template-columns: repeat(3, 1fr);
        }

        .option {
            margin-bottom:0;
            position:relative;
            &:hover{
                .delete{
                    display: block;
                }
            }
        }

        
    }

    .delete{
        color: $dangerColor;
        cursor: pointer;;
        position: absolute;
        right: 0;
        top: 0;
        z-index: 2;
        transform: translate(80%, -80%);
        display: none;
    }

</style>